using System;
using System.Runtime.InteropServices;
using System.Text;

namespace octalforty.Componento.Core.ApplicationServices.Impl
{
    public class CoConfig
    {
        private readonly string path;

        public CoConfig(string path)
        {
            this.path = path;
        }

        public void WriteValue(string section, string key, string value)
        {
            NativeMethods.WritePrivateProfileString(section, key, value, this.path);
        }

        public string ReadString(string section, string key)
        {
            var temp = new StringBuilder(255);
            var i = NativeMethods.GetPrivateProfileString(section, key, "", temp, 255, path);
            return temp.ToString();
        }

        public string[] ReadSection(string section)
        {
            const int bufferSize = 32768;

            var returnedString = new StringBuilder();

            var pReturnedString = Marshal.AllocCoTaskMem(bufferSize);
            try
            {
                var bytesReturned = NativeMethods.GetPrivateProfileSection(section, pReturnedString, bufferSize, path);

                //bytesReturned -1 to remove trailing \0
                for(var i = 0; i < bytesReturned - 1; i++)
                    returnedString.Append((char)Marshal.ReadByte(new IntPtr((uint)pReturnedString + (uint)i)));
            }
            finally
            {
                Marshal.FreeCoTaskMem(pReturnedString);
            }

            var sectionData = returnedString.ToString();
            return sectionData.Split('\0');
        }
    }
}